<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input :placeholder="$t('table.phone')" v-model="listQuery.mobile" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.isFreeze" :placeholder="$t('table.type')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in freezeOptions" :key="item" :label="item" :value="index"/>
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <router-link :to="'/user/create'">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          {{ $t('table.add') }}
        </el-button>
      </router-link>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center">
        <template slot-scope="scope">
          <el-link type="success" @click="toAddress(scope.row.id )">
            <span>{{ scope.row.id }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.nickname')" prop="nickname" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.phone')" prop="mobile" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.sex')" prop="sex" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex | sexFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.age')" prop="age" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ toAge(scope.row.birthday) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.status')" class-name="status-col" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isFreeze | statusFilter">{{ scope.row.isFreeze | freezeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.infractions')" prop="infractions" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.infractions }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.creationtime')" align="center" width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updatetime')" align="center" width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <!--   编辑按钮   -->
      <el-table-column :label="$t('table.actions')" align="center" width="290px">
        <template slot-scope="scope">
          <router-link :to="'/users/edit/'+scope.row.id">
            <el-button type="primary" size="small" icon="el-icon-edit">{{ $t('table.edit') }}</el-button>
          </router-link>
          <el-button v-if="scope.row.isFreeze === 1" size="mini" type="success" @click="freezeStatus(scope.row, 0)">{{ $t('table.thaw') }}
          </el-button>
          <el-button v-else size="mini" type="warning" @click="openFreeze(scope.row,1)">{{ $t('table.freeze') }}
          </el-button>
          <el-button size="mini" type="danger" @click="openDelete(scope.row.id)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import { getOptionsList, deleteUserById, freezeStatusById } from '@/api/user'
import waves from '@/directive/waves' // 按钮波浪样式
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页
import { toMessage } from '@/utils/hint' // 提示信息

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    // 性别的转换
    sexFilter(type) {
      if (type === 0) {
        return '女'
      } else {
        return '男'
      }
    },
    // 判断是否冻结
    freezeFilter(type) {
      if (type === 0) {
        return '正常'
      } else {
        return '冻结'
      }
    },
    statusFilter(status) {
      const statusMap = {
        0: 'success',
        1: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: { // 查询条件
        page: 1,
        limit: 20,
        mobile: undefined,
        isFreeze: undefined,
        sort: '+id'
      },
      freezeOptions: [this.$t('table.normal'), this.$t('table.freeze')], // 状态选项
      downloadLoading: false, // 下载加载
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }] // 按照id排序
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getOptionsList(this.listQuery).then(response => {
        this.list = response.data.extend.list
        this.total = response.data.extend.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    // 添加事件
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 下载zip
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [this.$t('table.id'), this.$t('table.nickname'), this.$t('table.phone'), this.$t('table.sex'), this.$t('table.age'), this.$t('table.creationtime')]
        const filterVal = ['id', 'nickname', 'phone', 'sex', 'birthday', 'creationTime']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'users-list'
        })
        this.downloadLoading = false
      })
    },
    // zip转json用
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 删除提示
    openDelete(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteOneUser(id)
      }).catch(() => {
        toMessage(this, 'info', '已取消删除')
      })
    },
    // 删除操作
    deleteOneUser(id) {
      deleteUserById(id).then(response => {
        if (response.data.code === 200) {
          toMessage(this, 'success', '删除成功!')
          this.getList()
        } else {
          toMessage(this, 'error', '删除失败')
        }
      })
    },
    // 冻结提示
    openFreeze(row, status) {
      this.$confirm('此操作将冻结该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.freezeStatus(row, status)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消冻结'
        })
      })
    },
    // 切换冻结状态
    freezeStatus(row, status) {
      const msg = status === 0 ? '解冻' : '冻结'
      freezeStatusById(row.id, status).then(response => {
        if (response.data.code === 200) {
          toMessage(this, 'success', msg + '成功!')
        } else {
          toMessage(this, 'error', msg + '失败')
        }
        this.getList()
      })
    },
    // 根据返回的日期计算间隔
    toAge(timeStamp) {
      const birthDate = this.toDate(timeStamp).substr(0, 4)
      const newDate = new Date().getFullYear()
      return (newDate - parseInt(birthDate))
    },
    // 时间戳转日期
    toDate(number) {
      const n = number
      const date = new Date(n)
      const Y = date.getFullYear() + '/'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/'
      const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return (Y + M + D)
    },
    // 跳转到地址列表
    toAddress(id) {
      this.$router.push({ name: 'AddressList', params: { id: id }})
    }
  }
}
</script>
